package com.heima.article.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ApArticleService;
import com.heima.common.constants.ArticleConstants;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.article.dtos.ArticleInfoDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.AppUserThreadLocalUtil;
import org.apache.commons.lang.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * @author Psycho
 * @create 2022-04-23-12:54
 */
@Service
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {

    private static final Integer MAX_PAGE_SIZE = 50;

    @Autowired
    private ApArticleMapper apArticleMapper;

    @Autowired
    private ApArticleConfigMapper apArticleConfigMapper;

    @Autowired
    private ApArticleContentMapper apArticleContentMapper;

    @Autowired
    private ArticleFreemarkerServiceImpl articleFreemarkerService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查找文章
     *
     * @param dto
     * @param loadtype loadtype 1为加载更多  2为加载最新
     * @return
     */
    @Override
    public ResponseResult loadByType(ArticleHomeDto dto, Short loadtype) {
        //先判断传入的前端数据是否正确
        //如果未给size赋值我们就要赋初始值
        Integer size = dto.getSize();
        if(size ==null && size ==0){
            size = 10;
        }
        //最大数据量为50
        size = Math.min(size,MAX_PAGE_SIZE);
        dto.setSize(size);

        //如果未指定时间，就以当前时间为基准
        if(dto.getMinBehotTime() == null)dto.setMinBehotTime(new Date());
        if(dto.getMinBehotTime() == null)dto.setMinBehotTime(new Date());

        //类型参数检验
        if(!loadtype.equals(ArticleConstants.LOADTYPE_LOAD_MORE)&&!loadtype.equals(ArticleConstants.LOADTYPE_LOAD_NEW)){
            loadtype = ArticleConstants.LOADTYPE_LOAD_MORE;
        }
        //文章频道校验
        if(StringUtils.isEmpty(dto.getTag())){
            dto.setTag(ArticleConstants.DEFAULT_TAG);
        }

        List<ApArticle> articleList = apArticleMapper.loadArticleList(dto, loadtype);
        return ResponseResult.okResult(articleList);
    }

    @Override
    public ResponseResult saveArticle(ArticleDto dto) {

//        try {
//            Thread.sleep(3000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }

        //检查参数
        if(dto == null || StringUtils.isBlank(dto.getContent())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //保存文章
        //1.构建文章的对象
        ApArticle apArticle = new ApArticle();
        //属性值的拷贝
        BeanUtils.copyProperties(dto,apArticle);
        //判断是新增还是修改
        if(apArticle.getId() == null){      //新增
            save(apArticle);

            //article_config的新增
            ApArticleConfig apArticleConfig = new ApArticleConfig(apArticle.getId());
            apArticleConfigMapper.insert(apArticleConfig);

            //article_content的新增
            ApArticleContent apArticleContent = new ApArticleContent();
            apArticleContent.setArticleId(apArticle.getId());
            apArticleContent.setContent(dto.getContent());
            apArticleContentMapper.insert(apArticleContent);

            articleFreemarkerService.buildArticleToMinIO(apArticle, dto.getContent());
        }
        //修改
        updateById(apArticle);
        //修改article_content
        ApArticleContent apArticleContent = apArticleContentMapper.selectOne(Wrappers.<ApArticleContent>lambdaQuery()
                .eq(ApArticleContent::getArticleId,apArticle.getId()));
        apArticleContent.setContent(dto.getContent());
        apArticleContentMapper.updateById(apArticleContent);
        articleFreemarkerService.buildArticleToMinIO(apArticle, dto.getContent());
        return ResponseResult.okResult(apArticle.getId());
    }

    /**
     * 数据的回显展示
     * @param dto
     * @return
     */
    @Override
    public ResponseResult showBack(ArticleInfoDto dto) {
        //获取登入用户
        ApUser user = AppUserThreadLocalUtil.getUser();
        String firstKey = dto.getArticleId()+"_";
        String secondKey = user.getId()+"_Like";

        Integer islike = (Integer) redisTemplate.opsForHash().get(firstKey, secondKey);

        HashMap<String, Boolean> map = new HashMap<>();
        map.put("islike",islike==0);
        map.put("isunlike",true);
        map.put("iscollection",false);
        map.put("isfollow",true);
        return ResponseResult.okResult(map);
    }
}
